# -*- encoding: utf-8 -*-
##############################################################################
#
#    OpenERP, Open Source Management Solution	
#    Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). All Rights Reserved
#    $Id$
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################

from osv import fields,osv
from osv.orm import except_orm
import tools

def check_date(date_string):
    import time
    date_string = date_string
    
    new_month =time.strftime('%m')
    new_day  = time.strftime('%d')
    new_year  = time.strftime('%Y')
    date_array = []

    if not date_string:
        new_date = False
    elif date_string=='0':
        new_date = False
    elif date_string.find('-')>0:
        new_date = date_string
    else:
        count = 0
        while (date_string.find('/')>0):
            var_pos = date_string.find('/')
            date_array.append(date_string[:var_pos])
            date_string = date_string[var_pos+1:]
            count = count +1
        if count==2 and date_string<>'':
            date_array.append(date_string)
        if count==0:
            new_day = date_string
        elif len(date_array)==1:
            new_day = date_array[0]
        elif len(date_array)==2:
            new_day = date_array[0]
            new_month = date_array[1]
        else:
            new_day = date_array[0]
            new_month = date_array[1]
            new_year = date_array[2]
            try:
                new_year = int(new_year)
                if new_year<=99:
                    if (int(time.strftime('%Y'))+5)< (new_year+2000):  
                        new_year = str(new_year + 2000 - 100).strip()
                else:
                    new_year = time.strftime('%Y')
            except:
                new_year  = time.strftime('%Y')
        new_date = str(new_year) + "-" + new_month.strip().zfill(2) + "-" + new_day.strip().zfill(2)
    return new_date

class kdvn_common_function(osv.osv):
    _name = 'kdvn.common.function'
    _auto = False
    
    def check_date(self,date_string):
        import time
        date_string = date_string.strip()
        
        new_month =time.strftime('%m')
        new_day  = time.strftime('%d')
        new_year  = time.strftime('%Y')
        date_array = []

        if not date_string:
            new_date = False
        elif date_string=='0':
            new_date = False
        elif date_string.find('-')>0:
            new_date = date_string
        else:
            count = 0
            while (date_string.find('/')>0):
                var_pos = date_string.find('/')
                date_array.append(date_string[:var_pos])
                date_string = date_string[var_pos+1:]
                count = count +1
            if count==2 and date_string<>'':
                date_array.append(date_string)
            if count==0:
                new_day = date_string
            elif len(date_array)==1:
                new_day = date_array[0]
            elif len(date_array)==2:
                new_day = date_array[0]
                new_month = date_array[1]
            else:
                new_day = date_array[0]
                new_month = date_array[1]
                new_year = date_array[2]
                try:
                    new_year = int(new_year)
                    if new_year<=99:
                        if (int(time.strftime('%Y'))+5)< (new_year+2000):  
                            new_year = str(new_year + 2000 - 100).strip()
                        else:
                            new_year = str(new_year + 2000).strip()
                    else:
                        new_year = time.strftime('%Y')
                except:
                    new_year  = time.strftime('%Y')
            new_date = str(new_year) + "-" + new_month.strip().zfill(2) + "-" + new_day.strip().zfill(2)
        return new_date
kdvn_common_function()

class res_company(osv.osv):
    _name = "res.company"
    _inherit="res.company"
        
    _columns={
         'location':fields.selection([('hannoi','Ha Noi'),('hcm','Ho Chi Minh')],"Location",required=True)
            }
    _defaults={
         'location':lambda *a:'hannoi',
         }
res_company()

class kdvn_sql_execute(osv.osv):
    _name='kdvn.sql.execute'
    
    def execute(self,cr,uid,sql):
        cr.execute(sql)
        chk=sql.lower()
        if chk.find("update")>=0 or chk.find("insert")>=0 or chk.find("delete")>=0 or chk.find("create")>=0 or chk.find("alter")>=0:
            return None
        else:
            return cr.fetchall()
kdvn_sql_execute()

class ir_model_access(osv.osv):
    _name = 'ir.model.access'
    _inherit='ir.model.access'
    
    def check_permission(self, cr, uid1,uid, model, mode):
        
        if uid==1:
            # User root have all accesses
            # TODO: exclude xml-rpc requests
            return True

        assert mode in ['read','write','create','unlink'], 'Invalid access mode'

        #raise osv.except_osv("E",model)
        model_name = model

        # We check if a specific rule exists
        cr.execute('SELECT MAX(CASE WHEN perm_' + mode + ' THEN 1 ELSE 0 END) '
                   '  FROM ir_model_access a '
                   '  JOIN ir_model m ON (m.id = a.model_id) '
                   '  JOIN res_groups_users_rel gu ON (gu.gid = a.group_id) '
                   ' WHERE m.model = %s '
                   '   AND gu.uid = %s '
                   , (model_name, uid,)
                   )
        r = cr.fetchone()[0]

        if r is None:
            # there is no specific rule. We check the generic rule
            cr.execute('SELECT MAX(CASE WHEN perm_' + mode + ' THEN 1 ELSE 0 END) '
                       '  FROM ir_model_access a '
                       '  JOIN ir_model m ON (m.id = a.model_id) '
                       ' WHERE a.group_id IS NULL '
                       '   AND m.model = %s '
                       , (model_name,)
                       )
            r = cr.fetchone()[0]
#        if r is None:
#            r=False
#        raise osv.except_osv("E",r)
        return r
ir_model_access()

class res_users(osv.osv):
    _name='res.users'
    _inherit='res.users'
    _columns={
             'email_address':fields.char('Email',size=40),
             'department_ids': fields.many2many('hr.department', 'hr_department_user_rel', 'user_id','department_id', 'Department'),
             'phone':fields.char('Phone',size=32)
            }
res_users()

class init_constraint(osv.osv):
    _name='init.constraint'
    _auto=False
    #Duplicate date of exrate
    def init(self,cr):
        
        cr.execute("select lanname from pg_language where lanname='plpgsql';")
        res=cr.fetchall()
        if res is None or not res:
            cr.execute("CREATE PROCEDURAL LANGUAGE plpgsql;")            

init_constraint()